from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, SelectField, ValidationError
from wtforms.validators import DataRequired, Length, Optional, EqualTo
from app.models.user import User
import re



class UserBaseForm(FlaskForm):
    def validate_username(self, field):
        if not re.match(r"^1[35678]\d{9}$", field.data):
            raise ValidationError('必须是手机号码')

        if User.query.filter_by(username=field.data).first():
            raise ValidationError('用户已被占用')

    def load(self, data):
        """填充数据
        """
        for k, v in data.__dict__.items():
            if hasattr(self, k):
                self.__dict__[k].data = '' if v is None else v


# 用户表单
class UserForm(UserBaseForm):
    username = StringField('用户名', validators=[DataRequired('必填'), Length(1, 20)])
    nickname = StringField('昵称', validators=[DataRequired('必填'), Length(1, 20)])
    password = PasswordField('密码', validators=[DataRequired('必填'), Length(6, 128, message='长度6-128个字符'), EqualTo('password2', message="必须与确认密码一致")])
    password2 = PasswordField('确认密码', validators=[DataRequired('必填'), Length(6, 128, message='长度6-128个字符')])
    submit = SubmitField('提交')


# 用户更新
class UserUpdateForm(UserBaseForm):
    nickname = StringField('昵称', validators=[DataRequired('必填'), Length(1, 20)])
    new_password = PasswordField('新密码', validators=[DataRequired(''), Length(6, 128, message='长度6-128个字符'), EqualTo('new_password2', message="必须与确认密码一致")])
    new_password2 = PasswordField('确认新密码', validators=[DataRequired(''), Length(6, 128, message='长度6-128个字符')])
    submit = SubmitField('更新')